#include "CProgram.h"
#include <stdlib.h>
#include <string.h>
#include <iostream>

using namespace std;

CProgram::CProgram (const CProgram &other): ProgramDate(other.getProgramDate())
{
for(int i=0;i<other.iExerciseCount;i++)
	addExercise(new CExercise(*other.getExercise(i)->getDevicePtr()),other.getProgramDate());
	
}

CProgram::CProgram(CDate Date) : ProgramDate(Date), iExerciseCount(0) {}

CProgram::~CProgram(void) { freeAll(); }

resAddDevice CProgram::addExercise(CExercise *E, CDate D)
{
CExercise **ExercisesTemp;
	if (E==NULL)
		return DEVICE_NULL;

	for(int i=0;i<this->getExerciseCount();i++)
		if (strcmp(E->getDevicePtr()->getDeviceName(),this->getExercise(i)->getDevicePtr()->getDeviceName())==0)
			return DEVICE_EXIST;

ExercisesTemp = new CExercise*[iExerciseCount+1];
	
	for(int i=0;i<iExerciseCount;i++)
		ExercisesTemp[i] = Exercises[i];

	ExercisesTemp[iExerciseCount] = E;

	if (iExerciseCount>0)
		delete []Exercises;
	
	Exercises = new CExercise*[iExerciseCount+1];
	for(int i=0;i<=iExerciseCount;i++)
		Exercises[i] = ExercisesTemp[i];

	delete []ExercisesTemp;

	ProgramDate = D;

	iExerciseCount++;

	return DEVICE_OK;
}

void CProgram::removeExercise(char *ExerciseName, CDate D)
{
CExercise **ExercisesTemp;
int FoundIndex=-1;
	for(int i=0;i<iExerciseCount;i++)
		if (strcmp(ExerciseName,Exercises[i]->getDevicePtr()->getDeviceName()))
		{
			FoundIndex = i;
			break;
		}
		if (FoundIndex == -1)
			return;

	ExercisesTemp = new CExercise*[iExerciseCount-1];

	for(int i=0;i<iExerciseCount;i++)
		if (i!=FoundIndex)	
			if (i<FoundIndex)
				ExercisesTemp[i] = Exercises[i];
			else
				ExercisesTemp[i-1] = Exercises[i];

		delete Exercises[FoundIndex];
		delete []Exercises;

	Exercises = new CExercise*[iExerciseCount-1];

	for(int i=0;i<iExerciseCount-1;i++)
		Exercises[i] = ExercisesTemp[i];

	delete []ExercisesTemp;
	
	iExerciseCount--;

	ProgramDate=D;	

}

void CProgram::setProgramDate(const CDate &D)
{
	ProgramDate = D;
}
CDate CProgram::getProgramDate() const 
{
	return ProgramDate;
}
void CProgram::freeAll()
{
	for(int i=0;i<iExerciseCount;i++)
		delete  Exercises[i];		
	if (iExerciseCount>0)
		delete Exercises;
}

int CProgram::getExerciseCount() const {return iExerciseCount;}
const CExercise * CProgram::getExercise(int ind) const {return Exercises[ind];}
